package Job;

import models.Movie;
import models.Project;
import org.jsoup.Jsoup;
import org.jsoup.helper.StringUtil;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import play.Logger;
import play.jobs.Every;
import play.jobs.Job;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: licco
 * Date: 2017/3/12
 * Time: 上午11:31
 */
@Every("3mn")
public class SearchMovieJob extends Job {

    public void doJob() {
        List<Project> projects = Project.findAll();
        projects.forEach(project -> {
            try {
                Logger.info("Maintenance job Start ...");
                Document document = Jsoup.connect(project.href).get();
                Element body = document.getElementById("body");
                Elements divs = body.select("table.post_table");
                for(Element table : divs) {
                    if(Arrays.asList("MKV 720P 无字片源", "MKV 720P无字片源").contains(table.select("p").text())) {
                        Elements trs = table.select("table.noborder").select("tr");
                        for(Element tr : trs) {
                            String first_url = "http://www.btbtt.co/" + tr.select("td").first().select("a").attr("href");
                            if(!StringUtil.isBlank(tr.select("td").first().text()) &&
                                    !tr.select("td").first().attr("class").equals("bold")) {
                                Movie movie = new Movie();
                                movie.groupName = project.groupName;
                                movie.name = tr.select("td").first().text();
                                movie.downloadNum = tr.select("td").get(2).text();
                                movie.time = tr.select("td").get(3).text();

                                Document second_document = Jsoup.connect(first_url).get();
                                movie.url = second_document.getElementById("body").select("a[href]").attr("href");
                                movie.type = Movie.T.MEDIUM;
                                if(Movie.count("url=?", movie.url) == 0) {
                                    movie.save();
                                }
                            }
                        }
                    }
                }
                Logger.info("Maintenance job End ...");
            } catch(IOException e) {
                e.printStackTrace();
            }
        });
    }


}
